import { useSelector, useDispatch } from "react-redux";
import { 
  login, 
  logout, 
  subscribe, 
  updateListDisplay, 
  updateOpenInNewWindow, 
  resetError 
} from "@/store/modules/userStore";

export function useUser() {
  const dispatch = useDispatch();
  const { 
    currentUser, 
    subscribes, 
    listDisplay, 
    openInNewWindow, 
    loading, 
    error 
  } = useSelector((state) => state.user);

  // 登录函数
  const handleLogin = async (email, code) => {
    return dispatch(login({ email, code })).unwrap();
  };

  // 注销函数
  const handleLogout = async () => {
    return dispatch(logout()).unwrap();
  };

  // 订阅函数
  const handleSubscribe = async (ids) => {
    return dispatch(subscribe(ids)).unwrap();
  };

  // 更新列表显示模式
  const handleUpdateListDisplay = async (mode) => {
    return dispatch(updateListDisplay(mode)).unwrap();
  };

  // 更新窗口打开模式
  const handleUpdateOpenInNewWindow = async (isOpen) => {
    return dispatch(updateOpenInNewWindow(isOpen)).unwrap();
  };

  // 清除错误
  const clearError = () => {
    dispatch(resetError());
  };

  return {
    // 状态
    currentUser,
    subscribes,
    listDisplay,
    openInNewWindow,
    loading,
    error,
    isLoggedIn: !!currentUser,
    
    // 操作方法
    login: handleLogin,
    logout: handleLogout,
    subscribe: handleSubscribe,
    updateListDisplay: handleUpdateListDisplay,
    updateOpenInNewWindow: handleUpdateOpenInNewWindow,
    clearError,
  };
}